package org.iot.iotserver.http.config;

import cn.hutool.core.util.ArrayUtil;
import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.plus.webapp.EnvConfiguration;
import org.eclipse.jetty.plus.webapp.PlusConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.webapp.*;

import javax.servlet.ServletContextListener;

/**
 * JettyServer 启动配置
 */
public class JettyServer {

    private final int port;

    private String resourceBase;

    private AnnotationConfiguration annotationConfiguration;

    private ServletContextListener servletContextListener;

    public JettyServer(int port) {
        this.port = port;
    }

    public void setAnnotationConfiguration(AnnotationConfiguration annotationConfiguration) {
        this.annotationConfiguration = annotationConfiguration;
    }

    public void setServletContextListener(ServletContextListener servletContextListener) {
        this.servletContextListener = servletContextListener;
    }

    public void setResourceBase(String resourceBase) {
        this.resourceBase = resourceBase;
    }

    /**
     * 启动服务
     * @throws Exception
     */
    public void start() throws Exception {
        // 创建一个 webapp 上下文
        WebAppContext context = new WebAppContext();
        context.setContextPath("/");
        context.setDisplayName("Jetty");
        context.setResourceBase(this.resourceBase);

        if(this.servletContextListener != null) {
            context.addEventListener(this.servletContextListener);
        }

        context.setParentLoaderPriority(true);

        // 自定义配置类
        Configuration[] configurations = {
                new WebInfConfiguration(),
                new WebXmlConfiguration(),
                new MetaInfConfiguration(),
                new FragmentConfiguration(),
                new EnvConfiguration(),
                new PlusConfiguration(),
                new JettyWebXmlConfiguration()
        };

        if(this.annotationConfiguration != null) {
            configurations = ArrayUtil.insert(configurations, 0, this.annotationConfiguration);
        }

        context.setConfigurations(configurations);
        context.setSessionHandler(new SessionHandler());

        // 构建 jetty 服务器
        Server server = new Server(this.port);
        server.setHandler(context);
        server.start();
        server.join();
    }

}
